<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\android\v7;


use think\Cache;
use think\Controller;
use app\api\model\Authority;
use think\db;
use think\Request;
use app\api\model\OrderModel;

class User extends Controller
{
    protected $model;
    protected $us;
    
    public function _initialize()
    {
        $this->model=new Authority();
        $this->us   =$this->model->check(1);
    }
    
    /**
     * 修改手机号
     */
    public function reset_mobile()
    {
        $data=$this->model->post(['code', 'new_mobile']);
        if (!is_mobile($data['new_mobile'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        $s_verify=Cache::get(md5($data['new_mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');
        }
        Cache::clear(md5($data['new_mobile']));
        $user=self::$user;
        if (db('user')->where(['mobile'=>$data['new_mobile'], 'status'=>['in', '0,1,2']])->find()) {
            r_date([], 300, '该手机号已注册用户端，请重新选择手机号');
        }
        $res=db('user')->where(['user_id'=>$user['user_id']])->update(['mobile'=>$data['new_mobile']]);
        if ($res !== false) {
            r_date();
        }
        r_date([], 300, '修改失败，请刷新后重试');
    }
    
    public function index(OrderModel $orderModel)
    {
        $retrun   =db('user')->field('user.user_id,user.work_tag,user.mobile,user.username,user.avatar,user.sex,user.state,st.store_name,st.store_id,user.number,user.reserve')->join('store st', 'st.store_id=user.store_id', 'left')->where(['user_id'=>$this->us['user_id']])->find();
        $BeginDate=date('Y-m-01', strtotime(date("Y-m-d", time())));
        $starttime=strtotime($BeginDate);
        $enttime  =strtotime(date('Y-m-d', strtotime("$BeginDate +1 month -1 day")));
        $quantity =db('order')->where(['created_time'=>['between', [$starttime, $enttime]], 'assignor'=>$this->us['user_id']])->select();//本月接单量
        
        
        $list=$m=$orderModel->table('order')
            ->alias('a')
            ->field('concat(p.province,c.city,u.county,a.addres) as  addres,a.contacts,co.con_time,a.order_id,a.state,a.assignor,go.title')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('user us', 'a.assignor=us.user_id', 'left')
            ->join('goods_category go', 'a.pro_id=go.id', 'left')
            ->join('contract co', 'a.order_id=co.orders_id', 'left')
            ->where('a.assignor', $this->us['user_id'])
            ->whereBetween('co.con_time', [$starttime, $enttime])
            ->order('co.con_time desc')
            ->whereBetween('a.state', [4, 7])->select();
        
        
        foreach ($list as $k=>$key) {
            $mouth=$orderModel->offer($key['order_id']);
            //签约金额
            $list[$k]['amount']=sprintf('%.2f', $mouth['amount']);
        }
       
        $amount            =sprintf('%.2f', array_sum(array_column($list, 'amount')));
    
        $zeng              =array_sum(array_column((new Financial)->zeng($starttime, $enttime, $this->us['user_id']), 'turnover'));
        $jian              =array_sum(array_column((new Financial)->jian($starttime, $enttime, $this->us['user_id']), 'turnover'));
        $tui               =array_sum(array_column((new Financial)->tui($starttime, $enttime, $this->us['user_id']), 'turnover'));
        $ye                =sprintf('%.2f', $amount + $zeng - $jian - $tui);
        $retrun['quantity']=count($quantity);
        $retrun['signing'] =$ye;
        $retrun['volume']  =(new Financial)->TurnoverRate('ss');
        
        $work_tag=empty($retrun['work_tag'])? [0, 0, 0, 0] : explode(',', $retrun['work_tag']);
        foreach ($work_tag as $k=>$value) {
            $k=$k + 1;
            switch ($value) {
                case 0:
                    $value='http://www.ynweixiu.art/shopowner/small/' . $k . '-grey-small.png';
                    break;
                case 1:
                    $value='http://www.ynweixiu.art/shopowner/small/' . $k . '-small.png';
                    break;
            }
            $date[]=$value;
        }
        $retrun['work_tag']=$date;
        
        r_date($retrun, 200, '获取成功');
    }
    
    public function Icon()
    {
        $work_tag=db('user')->where(['user_id'=>$this->us['user_id']])->value('work_tag');
        $work_tag=empty($work_tag)? [0, 0, 0, 0] : explode(',', $work_tag);
        foreach ($work_tag as $k=>$value) {
            
            switch ($k) {
                case 0:
                    $data['title']='建筑渗漏水维修专家';
                    break;
                case 1:
                    $data['title']='旧房改造类专家';
                    break;
                case 2:
                    $data['title']='墙面维修专家';
                    break;
                case 3:
                    $data['title']='室内渗漏水维修专家';
                    break;
            }
            $k=$k + 1;
            switch ($value) {
                case 0:
                    $data['img']='http://www.ynweixiu.art/shopowner/big/' . $k . '-grey.png';
                    break;
                case 1:
                    $data['img']='http://www.ynweixiu.art/shopowner/big/' . $k . '.png';
                    break;
            }
            $date[]=$data;
        }
        
        
        r_date($date, 200, '获取成功');
    }
    
    /**
     * 修改我的状态
     */
    public function state()
    {
        $data=$this->model->post(['state']);
        //店长在线时长统计
        db('online')->insertGetId(['user_id'=>$this->us['user_id'], 'startTime'=>time(), 'type'=>$data['state'], 'time'=>time()]);
        
        $res=db('user')->where(['user_id'=>$this->us['user_id']])->update(['state'=>$data['state']]);
        
        if ($res) {
            r_date([], 200);
        }
        r_date([], 300, '状态修改失败，请刷新后重试');
    }
    
    /**
     * 修改资料
     * invoice_type
     */
    public function edit()
    {
        $data=$this->model->post(['avatar']);
        $res =db('user')->where(['user_id'=>$this->us['user_id']])->update([
            'avatar'=>$data['avatar'],
        ]);
        if ($res !== false) {
            r_date([], 200);
        }
        r_date([], 300, '编辑失败，请刷新后重试');
    }
    
    
    public function Article()
    {
        $result=send_post(U_SRC . "/support/v1.article/all", []);
        
        
        return r_date(json_decode($result, true), 200);
    }
    
    public function Article_list()
    {
        $data  =$this->model->post(['category_id', 'limit', 'page']);
        $result=send_post(U_SRC . "/support/v1.article/lists", $data);
        
        return r_date(json_decode($result, true), 200);
    }
    
    /*
     * 免打扰
     */
    public function disturb()
    {
        $this->model->post(['type']);
        db('user')->where('user_id', $this->us['user_id'])->update(['disturb'=>2]);
        r_date([], 200);
    }
    
    /*
     * 获取地理位置
     */
    public function lat()
    {
        $data=$this->model->post(['lat', 'lng']);
        db('user')->where('user_id', $this->us['user_id'])->update(['lat'=>$data['lat'], 'lng'=>$data['lng']]);
        r_date(null, 200);
    }
    
    /*
     * 免打扰
     */
    public function about()
    {
        $da=db('about')->find();
        r_date($da, 200);
    }
    
    public function url()
    {
        $da['url']='http://public.yiniaoweb.com/static/help/storemanage/';
        r_date($da, 200);
    }
    
    /*
     * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
     */
    public function message()
    {
        
        $message=db('message')->field('type,content,order_id,already,id')->where(['user_id'=>$this->us['user_id']])->limit(0, 3)->orderRaw('already=1 desc,time desc')->select();
        $data   =[
            'data'  =>$message,
            'count1'=>db('message')->where(['user_id'=>$this->us['user_id'], 'type'=>['in', '2,3,4,6'], 'already'=>1])->count(),
            'count2'=>db('message')->where(['type'=>5, 'already'=>1, 'user_id'=>$this->us['user_id']])->count(),
            'count3'=>db('message')->where(['type'=>1, 'already'=>1, 'user_id'=>$this->us['user_id']])->count(),
            'count4'=>0,
            'count5'=>db('message')->where(['user_id'=>$this->us['user_id'], 'already'=>1])->count(),
        ];
        r_date($data, 200);
    }
    
    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_list()
    {
        //0全部1系统2订单5公司通知7未读
        $data=$this->model->post(['type', 'page'=>1, 'limit'=>10, 'title']);
        $me  =db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content']=['like', "%{$data['title']}%"];
            $me->where($map);
        }
        if ($data['type'] == 2) {
            $me->where(['type'=>['in', '3,4,6']]);
        } elseif ($data['type'] == 7){
            $me->where(['already'=>1]);
        } elseif ($data['type'] == 5){
            $me->where(['type'=>$data['type']]);
        } elseif ($data['type'] == 1){
            $me->where(['type'=>$data['type']]);
        }
        $message=$me->where(['user_id'=>$this->us['user_id']])->field('id,type,content,order_id,already')
            ->orderRaw('already=1 desc,time desc')
            ->page($data['page'], $data['limit'])
            ->select();
        r_date($message, 200);
    }
    
    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_info()
    {
        $data           =$this->model->post(['id']);
        $message        =db('message')->where('id', $data['id'])->field('type,content,order_id,already,time')->find();
        $message['time']=date('Y-m-d H:i:s');
        if ($message['already'] != 0) {
            db('message')->where('id', $data['id'])->update(['already'=>0, 'have'=>time()]);
        }
        
        r_date($message, 200);
    }
    
    /*
     * 储备店长
     */
    public function reserve()
    {
        $data  =$this->model->post();
        $chanel=db('user')
            ->field('user.number,user.username,user.mobile,user.lat,user.lng,user.user_id');
        if (isset($data['username']) && $data['username'] != '') {
            $chanel->where(['user.username'=>['like', "%{$data['username']}%"]]);
        }
        $list=$chanel->where(['status'=>0, 'reserve'=>2, 'store_id'=>$this->us['store_id']])
            ->order('status')
            ->select();
        r_date($list, 200);
    }
    
    /**
     * 获取后台客户注册的
     */
    public function jp()
    {
        $message=db('admin')->field('username,logo,admin_id')->where(['status'=>0, 'jp'=>1])->select();
        r_date($message, 200);
    }
    
    /**
     * 店铺
     * invoice_type
     */
    public function store()
    {
        $res=db('store')->field('store_id,store_name')->select();
        
        r_date($res, 200);
        
        
    }
    
    /**
     *工种
     * invoice_type
     */
    public function workType()
    {
        $res=Db::connect(config('database.db2'))->table('app_work_type')->whereNull('deleted_at')->where('status', 1)->field('id,title')->select();
        
        r_date($res, 200);
    }
//    public function get_order()
//    {
//
//        $start_time = strtotime(date("Y-m-d", time()));
//        //当天结束之间
//        $end_time = $start_time + 60 * 60 * 24;
//        $data     = $this->model->post(['state', 'page' => 1, 'limit' => 10]);
//        $m        = db('order')
//            ->alias('a')
//            ->field('a.order_id,a.ification,a.order_no,a.addres,a.contacts,a.telephone,a.remarks,a.created_time,a.state,a.quotation,a.planned,b.title,p.province,c.city,u.county,go.title')->join('chanel b', 'a.channel_id=b.id', 'left')
//            ->join('province p', 'a.province_id=p.province_id', 'left')
//            ->join('city c', 'a.city_id=c.city_id', 'left')
//            ->join('county u', 'a.county_id=u.county_id', 'left')
//            ->join('goods_category go', 'a.pro_id=go.id', 'left')
//            ->where(['a.assignor' => $this->us['user_id']]);
//
//
//        if ($data['state'] == 1) {
//            $m->where(['a.state' => 1])->order('a.planned desc');
//        } elseif ($data['state'] == 2) {
//            $m->where(['a.state' => 2])->order('a.update_time desc');
//        } elseif ($data['state'] == 3) {
//            $m->where(['a.through_id' => ['NEQ', 'NULL']])->order('a.order_id desc');
//        }
//
//        $list = $m->page($data['page'], $data['limit'])->select();
//        foreach ($list as $k => $key) {
//            $list[$k]['created_time'] = !empty($key['created_time']) ? date('Y-m-d H:i:s', $key['created_time']) : '';
//            $list[$k]['planned']      = !empty($key['planned']) ? date('Y-m-d H:i:s', $key['planned']) : '';
//            if ($data['state'] == 2) {
//
//            }
//            if ($data['state'] == 1) {
//
//            }
//
//            if ($data['state'] == 3) {
//                $thro = db('through')->where(['order_ids' => $key['order_id'], 'end_time' => ['between', [$start_time, $end_time]]])->order('th_time desc')->select();
//                if ($thro) {
//                    $list[$k]['msg'] = "今日需要跟进";
//                } else {
//                    $list[$k]['msg'] = null;
//                }
//
//            } else {
//                $list[$k]['msg'] = null;
//            }
//
//
//            $list[$k]['end_time'] = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : '';
//            if ($i) {
//                if ($data['orderType'] != 1) {
//                    unset($list[$k]);
//                }
//
//            } else {
//                $list[$k]['end_time'] = '';
//            }
//        }
//
//        r_date(array_merge($list));
//    }


}